package org.rjxh.examfront.service.impl;

import com.alibaba.fastjson.JSON;
import org.rjxh.examfront.pojo.*;
import org.rjxh.examfront.service.ICodeRunService;
import org.rjxh.examfront.service.IExamAnswerService;
import org.rjxh.examfront.service.IExamQuestionService;
import org.rjxh.examfront.web.tools.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Service
public class CodeRunServiceImpl implements ICodeRunService {
    @Resource
    private RestTemplate restTemplate;
    @Value("${code.run.url}")
    private String codeRunUrl;

    @Resource
    private RedisCache redisCache;

    @Resource
    private IExamAnswerService answerService;
    @Resource
    private IExamQuestionService questionService;

    Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public R<?> codeRun(CodeRequest codeRequest) {
        Long userId = ((LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUser().getUserId();

        Long questionId = codeRequest.getQuestionId();
        ExamQuestion examQuestion = questionService.getById(questionId);

        if (examQuestion == null) {
            return new R<>(500, "该问题不存在,无法匹配上下文代码");
        }
        examQuestion.reflectCode();
        //拼接代码段
        String umpireCode = examQuestion.getExamQuestionCode().getUmpireCode();
        String userSource = codeRequest.getSource();
        codeRequest.setSource(umpireCode + "\n" + userSource);


        logger.info("用户" + userId + "开始运行代码");
        logger.warn("用户" + userId + codeRequest.toString());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;charset=UTF-8"));
        // 请求头 & 请求体
        HttpEntity<JSON> fromEntity = new HttpEntity(JSON.toJSON(codeRequest), headers);


        CodeRespond codeRespondResponseEntity = null;
        CodeRespond codeResponseBody = null;
        try {
            ResponseEntity<CodeRespond> codeResponse = restTemplate.postForEntity(codeRunUrl, fromEntity, CodeRespond.class);
            codeResponseBody = codeResponse.getBody();
        } catch (RestClientException e) {
            return new R<>(500, "编译器出错误");
        }


        return new R<>(200, "操作成功", codeResponseBody);
    }

}

